package com.cskaoyan.javase.network._2tcp._v2;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端
 *
 * @since 15:16
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class Server {
    public static void main(String[] args) throws IOException {
        // 1.创建服务端的ServerSocket对象
        ServerSocket serverSocket = new ServerSocket(8888);
        // 2.开始监听客户端的连接,用accept方法,如果连接成功,该方法返回客户端的Socket对象
        Socket socket = serverSocket.accept();

        // 3.读取客户端发送的消息数据
        // 获取客户端的Socket对象的输入流(读数据)
        InputStream in = socket.getInputStream();
        byte[] buf = new byte[1024];
        String msg = "";
        while (!msg.equals("结束")) {
            int readCount = in.read(buf);
            msg = new String(buf, 0, readCount);
            System.out.println(socket.getRemoteSocketAddress() + "客户端发送的消息是:" + msg);
        }
        // 4.close关闭
    }
}
